var queryParamList = {};

$.extend(true, $.fn.dataTable.defaults, {
    "sDom": "R<'row'<''f>r>t<'len-menu-l'l><'paginate-r'<'paginate-r'p<'page-row-r'<'row-left-info'i>>>",
    "sPaginationType": "bootstrap",
    "bServerSide": true, //分页，取数据等等的都放到服务端去
    "bProcessing": true, //载入数据的时候是否显示“载入中”
    "aLengthMenu": [10, 15, 30, 50, 100],
    "bLengthChange": false, //改变每页显示数据数量
    "bFilter": false, //过滤功能
    "iDisplayStart": 0,
    "iDisplayLength": 10, //首次加载的数据条数
    "bStorable": false, //排序操作在服务端进行，所以可以关了。
    "bSort": true,
    "username": "yishuaijun",
    "oLanguage": {
        "sSearch": "搜索",
        sZeroRecords: "没有找到匹配的数据",
        "sLengthMenu": "每页 _MENU_ 条",
        "sInfo": "&nbsp;&nbsp;从 _START_ 到 _END_ ,  共 _TOTAL_ 条",
        "sInfoEmpty": "没有记录",
        "sInfoFiltered": "(从 _MAX_ 条记录中搜索)",
        "oPaginate": {
            "sFirst": "第一页",
            "sPrevious": "« 上一页",
            "sNext": "下一页 »",
            "sLast": "最后一页"
        },
        "sProcessing": "<img src='/images/loading.gif' />"

    },
    "fnServerData": function (sSource, aoData, fnCallback, bStorable) {
        var sortStrs = $.getSortingFields(bStorable.aoColumns, bStorable.aaSorting);
        queryParamList.sEcho = 0;
        queryParamList.iDisplayLength = 0;
        queryParamList.iDisplayStart = 0;
        queryParamList.iSorts = sortStrs;

        for (var i = 0; i < aoData.length; i++) {
            if (aoData[i].name == "iDisplayStart") {
                queryParamList.iDisplayStart = aoData[i].value;
            } else if (aoData[i].name == "iDisplayLength") {
                queryParamList.iDisplayLength = aoData[i].value;
            } else if (aoData[i].name == "sEcho") {
                queryParamList.sEcho = aoData[i].value;
            }
        }
        $.ajax({
            "dataType": 'json',
            "type": "POST",
            "url": sSource,
            "data": queryParamList,
            "success": function (resp) {
                fnCallback(resp); //服务器端返回的对象的returnObject部分是要求的格式
                // queryParamList = {};//查询完毕后将查询参数对象置空
            },
            error: function (error) {
                console.log(error.responseText);
            }
        });
    },
    "fnRowCallback": function (nRow, aData, iDisplayIndex) {
        return nRow;
    }
});

/* API method to get paging information */
$.fn.dataTableExt.oApi.fnPagingInfo = function (oSettings) {
    return {
        "iStart": oSettings._iDisplayStart,
        "iEnd": oSettings.fnDisplayEnd(),
        "iLength": oSettings._iDisplayLength,
        "iTotal": oSettings.fnRecordsTotal(),
        "iFilteredTotal": oSettings.fnRecordsDisplay(),
        "iPage": Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength),
        "iTotalPages": Math.ceil(oSettings.fnRecordsDisplay() / oSettings._iDisplayLength)
    };
}

$.extend({
    getSortingFields: function (aoColumns, aaSorting) {
        var result = "";
        for (var i = 0; i < aaSorting.length; i++) {
            var a = aaSorting[i];
            var sortField = aoColumns[a[0]].mDataProp || aoColumns[a[0]].mData;
            if (sortField) {
                result += sortField + " " + a[1] + ",";
            }
        }
        return result.substring(0, result.length - 1);
    }
});


/* Bootstrap style pagination control */
$.extend($.fn.dataTableExt.oPagination, {
    "bootstrap": {
        "fnInit": function (oSettings, nPaging, fnDraw) {
            var oLang = oSettings.oLanguage.oPaginate;
            var fnClickHandler = function (e) {
                e.preventDefault();
                if (oSettings.oApi._fnPageChange(oSettings, e.data.action)) {
                    fnDraw(oSettings);
                }
            };

            $(nPaging).append(
               '<ul class="pagination">' +
                   '<li class="first disabled"><a href="#" title="' + oLang.sFirst + '">' + oLang.sFirst + '</a></li>' +
                   '<li class="prev disabled"><a href="#" title="' + oLang.sPrevious + '">' + oLang.sPrevious + '</a></li>' +
                   '<li class="next disabled"><a href="#" title="' + oLang.sNext + '">' + oLang.sNext + '</a></li>' +
                   '<li class="last disabled"><a href="#" title="' + oLang.sLast + '">' + oLang.sLast + '</a></li>' +
               '</ul>'
           );
            var els = $('a', nPaging);
            $(els[0]).bind('click.DT', { action: "first" }, fnClickHandler);
            $(els[1]).bind('click.DT', { action: "previous" }, fnClickHandler);
            $(els[2]).bind('click.DT', { action: "next" }, fnClickHandler);
            $(els[3]).bind('click.DT', { action: "last" }, fnClickHandler);
        },

        "fnUpdate": function (oSettings, fnDraw) {
            var iListLength = 5;
            var oPaging = oSettings.oInstance.fnPagingInfo();
            var an = oSettings.aanFeatures.p;
            var i, j, sClass, iStart, iEnd, iHalf = Math.floor(iListLength / 2);

            if (oPaging.iTotalPages < iListLength) {
                iStart = 1;
                iEnd = oPaging.iTotalPages;
            }
            else if (oPaging.iPage <= iHalf) {
                iStart = 1;
                iEnd = iListLength;
            } else if (oPaging.iPage >= (oPaging.iTotalPages - iHalf)) {
                iStart = oPaging.iTotalPages - iListLength + 1;
                iEnd = oPaging.iTotalPages;
            } else {
                iStart = oPaging.iPage - iHalf + 1;
                iEnd = iStart + iListLength - 1;
            }

            for (i = 0, iLen = an.length ; i < iLen ; i++) {
                // Remove the middle elements
                $('li:gt(1)', an[i]).filter(':not(:last)').filter(':not(:last)').remove();

                // Add the new list items and their event handlers
                for (j = iStart ; j <= iEnd ; j++) {
                    var anLen = $('li', an[i]).length - 1;
                    sClass = (j == oPaging.iPage + 1) ? 'class="active"' : '';
                    $('<li ' + sClass + '><a href="#">' + j + '</a></li>')
                        .insertBefore($('li:lt(' + anLen + ')', an[i])[anLen - 1])
                        .bind('click', function (e) {
                            e.preventDefault();
                            oSettings._iDisplayStart = (parseInt($('a', this).text(), 10) - 1) * oPaging.iLength;
                            fnDraw(oSettings);
                        });
                }

                // Add / remove disabled classes from the static elements
                if (oPaging.iPage === 0) {
                    $('li:first', an[i]).addClass('disabled');
                    $('li:first', an[i]).next().addClass('disabled');
                } else {
                    $('li:first', an[i]).removeClass('disabled');
                    $('li:first', an[i]).next().removeClass('disabled');
                }

                if (oPaging.iPage === oPaging.iTotalPages - 1 || oPaging.iTotalPages === 0) {
                    $('li:last', an[i]).addClass('disabled');
                    $('li:last', an[i]).prev().addClass('disabled');
                } else {
                    $('li:last', an[i]).removeClass('disabled');
                    $('li:last', an[i]).prev().removeClass('disabled');
                }
            }
        }
    }
});